package com.jinke.api.common.annotation;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 同一个接口在限制时间内不能访问过于频繁的限制
 */
@Aspect
@Component
public class RateLimitInterceptor {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


//    @Pointcut("@annotation(com.jinke.api.common.annotation.RateLimit)")
//    public void pointcutOne() {
//
//    }

//    @Around("@annotation(com.jinke.api.common.annotation.RateLimit)")
    @Around("@annotation(rateLimitAnnotation)")
    public Object rateLimit(ProceedingJoinPoint joinPoint, RateLimit rateLimitAnnotation) throws Throwable {
        String key = rateLimitAnnotation.key();
        long timeSeconds = rateLimitAnnotation.timeSeconds();

        if (redisTemplate.hasKey(key)) {
            // 如果 key 存在，说明在限制时间内已经有过请求，返回错误信息或进行其他处理
            return "Too many requests within a short time.";
        } else {
            // 如果 key 不存在，设置 key 并设置过期时间
            redisTemplate.opsForValue().set(key, "in progress", timeSeconds, TimeUnit.SECONDS);
            return joinPoint.proceed();
        }
    }
}